import React, { useEffect } from 'react'
import { BrowserRouter, withRouter } from 'react-router-dom'

let prevLocation = null
let location = null
let action = null
let unBlock = null
let cancelListen = null

function _GuradHelper(props) {

    const { onChange } = props

    const { block, listen } = props.history

    useEffect(() => {
        // 添加阻塞
        unBlock = block((newLocation, ac) => {
            prevLocation = props.location
            location = newLocation
            action = ac
            return ''
        })

        // 添加一个监听器
        cancelListen = listen((location, action) => {
            onChange?.(props.location, location, action, cancelListen)
        })

        return () => {
            // 取消阻塞
            unBlock()
            cancelListen()
            prevLocation = null
            location = null
            action = null
            unBlock = null
            cancelListen = null
        }
    })

    return null
}

const GuradHelper = withRouter(_GuradHelper)

function RouteGuard({
    children,
    onChange,
    onBeforeChange,
    ...props
}) {

    const handleConfirm = (message, commit) => {
        if(onBeforeChange) {
            onBeforeChange({
                prevLoc: prevLocation,
                currLoc: location,
                ac: action,
                commit,
                unBlock
            })
        } else {
            commit(true) // 默认允许跳转
            // unBlock() // 取消阻塞
            // onChange?.(prevLocation, location, action, cancelListen) // 通知路由变化
            // prevLocation = null
            // location = null
            // action = null
            // unBlock = null
            // cancelListen = null // 取消监听，仅监听一次
            // return true // 允许跳转
        }
    }

    return (
        <BrowserRouter
            getUserConfirmation={handleConfirm}
        >
            <GuradHelper onChange={onChange} />
            {children}
        </BrowserRouter>
    )
}



export default RouteGuard